package ai;

import engine.GameEngine;
import engine.data.Map;
import util.ArrayList;
import util.List;

public class Node implements Trackable {

	public short x;

	public short y;

	public short f;
	public short g;
	public short h;

	public Node parent;

	public Node(short x, short y) {
		super();
		this.x = x;
		this.y = y;
		this.parent = null;
	}

	public short getX() {
		return x;
	}

	public short getY() {
		return y;
	}

	public short getG(Node end, Node parent, Map map, byte[][] influenceMapping, boolean isExploring, boolean isRunningAway) {
		boolean seen = map.hasBeenSeen(GameEngine.currPlayer, this.x, this.y);
		if (this.parent != null && seen)
			return (short) (parent.g + 1 + map.getTerrain(this.x, this.y).getMPC() + influenceMapping[this.x][this.y]);
		else if (this.parent != null && !seen)
			return (short) (parent.g + 1 + influenceMapping[this.x][this.y]);
		else
			return (short) (1 + influenceMapping[this.x][this.y]);

	}

	public short getH(Node end, Node parent, Map map, byte[][] influenceMapping, boolean isExploring, boolean isRunningAway) {
		if (isExploring)
			return 0;
		else if (isRunningAway)
			return (short) (Short.MAX_VALUE / 2 - (PathFinding.getHeuristic(this.x, this.y, end.x, end.y)));
		else
			return PathFinding.getHeuristic(this.x, this.y, end.x, end.y);
	}

	public void setGHF(Node end, Map map, byte[][] influenceMapping, boolean isExploring, boolean isRunningAway) {
		this.g = getG(end, this.parent, map, influenceMapping, isExploring, isRunningAway);
		this.h = getH(end, this.parent, map, influenceMapping, isExploring, isRunningAway);
		this.f = (short) (this.g + this.h);
	}

	public List getNeighbors() {
		List neighbors = new ArrayList();
		for (short i = -1; i <= 1; i++) {
			for (short j = -1; j <= 1; j++) {
				if (i != 0 || j != 0) {
					neighbors.add(new short[] {(short) (this.x + i), (short) (this.y + j)});
				}
			}
		}
		return neighbors;
	}
	public boolean equals(Node obj) {
		return this.x == obj.x && this.y == obj.y;
	}

	public String toString() {
		return new StringBuffer("(").append(this.x).append(", ").append(this.y).append(" - fgh= ").append(this.f).append(", ").append(this.g).append(", ").append(this.h).append(")\n").toString();
	}

}
